from flask import jsonify, request, redirect, url_for, render_template, Response, flash
from flask_login import current_user
from datetime import datetime
from models import db, User, GestureRecord
import logging

logger = logging.getLogger(__name__)

def user_management():
    if not current_user.is_authenticated or current_user.role != 'admin':
        return redirect(url_for('recognition'))
    users = User.query.all()
    return render_template('user_management.html', users=users)

def add_user():
    if not current_user.is_authenticated or current_user.role != 'admin':
        return jsonify({'success': False, 'error': '权限不足'})
    
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    role = data.get('role', 'user')
    
    if not username or not password:
        return jsonify({'success': False, 'error': '用户名和密码不能为空'})
    
    if User.query.filter_by(username=username).first():
        return jsonify({'success': False, 'error': '用户名已存在'})
    
    try:
        new_user = User(username=username)
        new_user.set_password(password)
        new_user.role = role
        db.session.add(new_user)
        db.session.commit()
        logger.info(f"管理员 {current_user.username} 添加了新用户 {username}")
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        logger.error(f"添加用户时出错: {str(e)}")
        return jsonify({'success': False, 'error': '添加用户失败'})

def delete_user(user_id):
    if not current_user.is_authenticated or current_user.role != 'admin':
        return jsonify({'success': False, 'error': '权限不足'})
    
    user = User.query.get_or_404(user_id)
    if user.id == current_user.id:
        return jsonify({'success': False, 'error': '不能删除当前登录用户'})
    
    try:
        db.session.delete(user)
        db.session.commit()
        logger.info(f"管理员 {current_user.username} 删除了用户 {user.username}")
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除用户时出错: {str(e)}")
        return jsonify({'success': False, 'error': '删除用户失败'})

def export_history():
    try:
        records = GestureRecord.query.filter_by(user_id=current_user.id).order_by(GestureRecord.timestamp.desc()).all()
        
        # 创建TXT内容
        txt_content = "手势识别记录\n"
        txt_content += "=" * 50 + "\n\n"
        
        for record in records:
            txt_content += f"时间：{record.timestamp.strftime('%Y-%m-%d %H:%M:%S')}\n"
            txt_content += f"手势：{record.gesture}\n"
            txt_content += f"内容：{record.content}\n"
            txt_content += "-" * 50 + "\n"
        
        # 设置响应头
        response = Response(
            txt_content,
            mimetype='text/plain',
            headers={
                'Content-Disposition': f'attachment; filename=gesture_history_{datetime.now().strftime("%Y%m%d_%H%M%S")}.txt'
            }
        )
        return response
    except Exception as e:
        logger.error(f"导出历史记录时出错: {str(e)}")
        flash('导出历史记录失败')
        return redirect(url_for('history')) 